<template>
  <div class="form-input-area" style="position: relative">
    <Spin :withIcon="true" v-if="loading"></Spin>
    <!-- <span class="submit-button-style-first f-14 c-o f-w-600">从我的域名列表选择域名</span> -->
    <div class="flx-row-s-c div-line long-name-nece" style="margin-top: 20px">
      <div class="long-name">模板名称</div>
      <Input
        v-model.trim="name"
        placeholder="请输入模板名称"
        style="width: 300px"
      />
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">模板类型</div>
      <RadioGroup v-model="type">
        <Radio class="radio-mg-r-20" :label="0">个人</Radio>
        <Radio class="radio-mg-r-20" :label="1">企业</Radio>
      </RadioGroup>
    </div>
    <template v-if="type == 1">
      <div class="flx-row-s-c div-line">
        <div class="flx-row-s-c long-name-nece">
          <div class="long-name">企业名称（中文）</div>
          <Select
            v-model="certificateId"
            filterable
            style="width: 250px"
            placeholder="请选择"
            :label-in-value="true"
            @on-change="companyChange"
          >
            <Option
              v-for="item in companyList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </div>

        <router-link
          to="/user/companyc"
          class="form-font-button f-w-600 pub-font-16"
          style="margin-left: 37px"
          >+企业认证</router-link
        >
      </div>
      <div class="flx-row-s-c div-line long-name-nece">
        <div class="long-name">企业名称（英文）</div>
        <Input
          v-model.trim="intBusinessName"
          placeholder="请输入英文名"
          style="width: 250px"
        />
      </div>
    </template>
    <div class="flx-row-s-c div-line">
      <div class="long-name-nece flx-row-s-c">
        <div class="long-name">姓名（中文）</div>
        <Select
          v-model="cardId"
          filterable
          style="width: 250px"
          placeholder="请选择"
          @on-change="nameChange"
        >
          <Option v-for="item in nameList" :value="item.id" :key="item.id">{{item.name}} - {{item.type | typeFilter}}</Option>
        </Select>
      </div>

      <router-link
        to="/user/personalc"
        class="form-font-button f-w-600 pub-font-14"
        style="margin-left: 37px"
        >+身份认证</router-link
      >
    </div>
    <div class="flx-row-s-c div-line">
      <div class="long-name-nece flx-row-s-c">
        <div class="long-name">姓名（英文）</div>
        <Input
          v-model.trim="intName"
          placeholder="请输入英文名"
          style="width: 250px"
        />
      </div>

      <span class="f-g f-14" style="margin-left: 37px"
        >为保证模块可审核通过，请勿轻易修改英文姓名。</span
      >
    </div>
    <div class="flx-row-s-c div-line">
      <div class="flx-row-s-c long-name-nece">
        <div class="long-name">邮箱</div>
        <Select
          v-model="emailId"
          filterable
          style="width: 250px"
          placeholder="请选择"
          @on-change="emailChange"
        >
          <Option v-for="item in emailList" :value="item.id" :key="item.id">{{
            item.name
          }}</Option>
        </Select>
      </div>

      <router-link
        to="/user/emailc"
        class="form-font-button f-w-600 pub-font-14"
        style="margin-left: 37px"
        >+邮箱认证</router-link
      >
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">国家</div>
      <Select
        v-model="countryId"
        filterable
        style="width: 300px"
        placeholder="请选择"
        @on-change="changeCountry"
      >
        <Option
          v-for="(item, index) in countryList"
          :value="item.id"
          :key="'c' + index"
          >{{ item.countryNameCn }}</Option
        >
      </Select>
    </div>
    <div class="flx-row-s-c div-line long-name-nece" v-if="countryId == 1">
      <div class="long-name">省份 城市</div>
      <Select
        v-model="province"
        filterable
        style="width: 120px; margin-right: 10px"
        @on-change="changeProvince"
      >
        <Option
          v-for="(item, index) in provinceList"
          :value="item.value"
          :key="'p' + index"
          >{{ item.label }}</Option
        >
      </Select>
      <Select
        v-if="province != null && province != ''"
        v-model="city"
        style="width: 120px; margin-right: 10px"
        filterable
        @on-change="changeCity"
      >
        <Option
          v-for="item in cityList"
          :value="item.value"
          :key="item.value"
          >{{ item.label }}</Option
        >
      </Select>
      <Select
        v-if="province != null && province != '' && city != null && city != ''"
        v-model="areas"
        filterable
        style="width: 120px"
      >
        <Option
          v-for="item in areaList"
          :value="item.value"
          :key="item.value"
          >{{ item.label }}</Option
        >
      </Select>
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">联系地址</div>
      <Input
        v-model.trim="locStreet2"
        placeholder="请您输入您的联系地址"
        style="width: 300px"
        maxlength="120"
      />
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">邮政编码</div>
      <Input
        v-model.trim="pc"
        placeholder="请您输入邮政编码"
        style="width: 300px"
      />
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">联系电话</div>
      <div class="gray-box">{{ phoneCode }}</div>
      <Input
        v-model.trim="voice"
        placeholder="请您输入联系电话"
        style="width: 270px"
      />
    </div>
    <div class="flx-row-s-c div-line long-name-nece">
      <div class="long-name">传真号码</div>
      <div class="gray-box">{{ phoneCode }}</div>
      <Input
        v-model.trim="fax"
        placeholder="请您输入传真号码"
        style="width: 270px"
      />
    </div>
    <div
      class="user-strong-button submit-button-style"
      style="margin: 50px 0 0 145px"
      @click="submit"
    >
      添加模板
    </div>
  </div>
</template>

<script>
import { validMobile } from "@/utils/validate.js";
import { countryList } from "@/utils/publicData";
import { getCertificatesSelectList, addTemplate } from "@/api/user";
import { convertToPinyin } from "@/utils/ConvertToPinyin";
export default {
  name: "VipTemplateAdd",
  filters: {
    typeFilter(val) {
      let title = "--";
      switch (val) {
        case 0:
          title = "身份证";
          break;
        case 1:
          title = "护照";
          break;
        case 2:
          title = "军官证";
          break;
        case 3:
          title = "港澳居民来往内地通行证";
          break;
        case 4:
          title = "港澳居民居住证";
          break;
        case 5:
          title = "台湾居民来往大陆通行证";
          break;
        case 6:
          title = "台湾居民居住证";
          break;
        case 7:
          title = "外国人永久居留身份证";
          break;
      }
      return title;
    },
  },
  data() {
    return {
      loading: false,
      countryList: [],
      // 表单数据
      name: "",
      type: 0,

      // 企业认证信息
      certificateId: null,
      locBusinessName: "",
      intBusinessName: "",
      companyList: [],

      // 个人认证信息
      cardId: null,
      locName: "",
      intName: "",
      nameList: [],

      // 邮箱认证信息
      emailId: null,
      email: "",
      emailList: [],

      countryId: 1,
      cc: "CN",
      phoneCode: 86,
      country: "中国",
      provinceList: [],
      province: "",
      cityList: [],
      city: "",
      areaList: [],
      areas: "",
      locStreet2: "",
      pc: "",
      voice: "",
      fax: "",

      areaCode:'',// 区号
    };
  },
  created() {
    this.getCountryList();
    this.getCertificatesSelectList();
    if (this.$route.params.data) {
      let temp = this.$route.params.data;
      this.name = temp.name;
      this.type = temp.type;
      this.certificateId = temp.certificateId;
      this.locBusinessName = temp.locBusinessName;
      this.intBusinessName = temp.intBusinessName;
      this.cardId = temp.cardId;
      this.locName = temp.locName;
      this.intName = temp.intName;
      this.emailId = temp.emailId;
      this.email = temp.email;
      this.countryId = temp.countryId;
      this.cc = temp.cc;
      this.phoneCode = temp.phoneCode;
      this.country = temp.country;
      this.province = temp.locSp;
      this.city = temp.locCity;
      this.areas = temp.locStreet;
      this.locStreet2 = temp.locStreet2;
      this.pc = temp.pc;
      this.voice = temp.voice;
      this.fax = temp.fax;
    }
  },
  methods: {
    // 选择的企业名称改变
    companyChange(item) {
      this.intBusinessName = convertToPinyin(item.label);
    },
    // 获取认证选项
    async getCertificatesSelectList() {
      let res = await getCertificatesSelectList();
      if (res.code == 200) {
        this.companyList = res.data.enterpriseList;
        this.nameList = res.data.identityList;
        this.emailList = res.data.emailList;
      }
    },
    // 获取省市区
    async getCountryList() {
      let res = await countryList();
      if (res != null) {
        this.countryList = res.country;
        this.provinceList = res.province;
        if (this.$route.params.data) {
          for (let i in this.countryList) {
            if (this.countryList[i].countryNameCn == this.country) {
              this.countryId = this.countryList[i].id;
              break;
            }
          }
          for (let i in this.provinceList) {
            if (this.provinceList[i].value == this.province) {
              this.cityList = this.provinceList[i].children;
              break;
            }
          }
          for (let i in this.cityList) {
            if (this.cityList[i].value == this.city) {
              this.areaCode = this.cityList[i].code
              this.areaList = this.cityList[i].children;
              break;
            }
          }
        }
      }
    },
    // 国家改变
    changeCountry() {
      for (let i in this.countryList) {
        if (this.countryList[i].id == this.countryId) {
          this.cc = this.countryList[i].countryShortName;
          this.phoneCode = this.countryList[i].countryCode;
          this.country = this.countryList[i].countryNameCn;
          break;
        }
      }
    },
    // 身份认证选择改变
    nameChange() {
      for (let i in this.nameList) {
        if (this.nameList[i].id == this.cardId) {
          this.locName = this.nameList[i].name;
          this.intName = convertToPinyin(this.locName);
          break;
        }
      }
    },
    // 邮箱选择改变
    emailChange() {
      for (let i in this.emailList) {
        if (this.emailList[i].id == this.emailId) {
          this.email = this.emailList[i].name;
          break;
        }
      }
    },
    // 省改变
    changeProvince() {
      for (let i in this.provinceList) {
        if (this.provinceList[i].value == this.province) {
          this.cityList = this.provinceList[i].children;
          break;
        }
      }
      this.city = "";
      this.areas = "";
    },
    // 城市改变
    changeCity() {
      for (let i in this.cityList) {
        if (this.cityList[i].value == this.city) {
          this.areaCode = this.cityList[i].code
          this.areaList = this.cityList[i].children;
          break;
        }
      }
      this.areas = "";
    },
    // 提交
    async submit() {
      if (!this.name) {
        this.$Message.warning("请输入模板名称！");
        return;
      }
      if (!this.type == null) {
        this.$Message.warning("请选择模板类型！");
        return;
      }
      if (this.type == 1) {
        if (!this.certificateId) {
          this.$Message.warning("请选择企业名称（中文）！");
          return;
        }
        if (!this.intBusinessName) {
          this.$Message.warning("请输入企业名称（英文）！");
          return;
        }
      }
      if (!this.cardId) {
        this.$Message.warning("请选择姓名（中文）！");
        return;
      }
      if (!this.intName) {
        this.$Message.warning("请输入姓名（英文）！");
        return;
      }
      if (!this.emailId) {
        this.$Message.warning("请选择邮箱！");
        return;
      }
      if (!this.countryId) {
        this.$Message.warning("请选择国家！");
        return;
      }
      if (!this.province || !this.city || !this.areas) {
        this.$Message.warning("请选择省份-城市！");
        return;
      }
      if (!this.locStreet2) {
        this.$Message.warning("请输入联系地址！");
        return;
      }else if(this.locStreet2.length < 5 || this.locStreet2.length > 120){
         this.$Message.warning("联系地址最小长度为5个字符,最大120字符！");
        return;
      }
      if (!this.pc) {
        this.$Message.warning("请输入邮政编码！");
        return;
      }
      if (!this.voice) {
        this.$Message.warning("请输入联系电话！");
        return;
      }else{
        let telephoneRegex = /^0\d{2,3}-\d{7,8}$/; // 座机号（带区号）校验
        let telephoneRegex2 = /^\d{7,8}$/;// 座机号（不带区号）校验
        // 手机号
        if(!validMobile(this.voice)){
            if(telephoneRegex.test(this.voice)){
              // 获取输入的区号
              let areaCode = this.voice.split('-')[0]
              let arr = this.areaCode.split('/')
              if(arr.length > 1){
                if(arr.indexOf(areaCode) === -1){
                  this.$Message.warning(`联系电话区号与城市区号不对应！当前城市区号为${this.areaCode}`);
                  return;
                }
              }else{
                if(areaCode !== this.areaCode){
                  this.$Message.warning(`联系电话区号与城市区号不对应！当前城市区号为${this.areaCode}`);
                  return;
                }
              }
            }else if(!telephoneRegex2.test(this.voice)){
                this.$Message.warning(`联系电话格式错误`);
                return;
            }else{
              console.log(this.areaCode)
              let arr = this.areaCode.split('/')
              if(arr.length > 0){
                this.voice = `${arr[0]}-${this.voice}`
              }else{
                this.voice = `${this.areaCode}-${this.voice}`
              }
            }
        }
      }
      if (!this.fax) {
        this.$Message.warning("请输入传真号码！");
        return;
      }
      let data = {
        name: this.name,
        type: this.type,
        cardId: this.cardId,
        locName: this.locName,
        intName: this.intName,
        emailId: this.emailId,
        email: this.email,
        cc: this.cc,
        country: this.country,
        locStreet2: this.locStreet2,
        pc: this.pc,
        voice: this.voice,
        fax: this.fax,
        phoneCode: this.phoneCode,
      };
      if (this.type == 1) {
        data.certificateId = this.certificateId;
        data.locBusinessName = this.locBusinessName;
        data.intBusinessName = this.intBusinessName;
      }
      if (this.countryId == 1) {
        data.locSp = this.province;
        data.locCity = this.city;
        data.locStreet = this.areas;
      }
      this.loading = true;
      let res = await addTemplate(data);
      if (res.code == 200) {
        this.$Message.success("添加成功！");
        let fromTemp = this.$storage.getFromPo();
        if (fromTemp) {
          this.$storage.setFromPo(false);
          setTimeout(() => {
            window.open("/pro");
          }, 1000);
        } else {
          this.$router.replace("/user/template");
        }
      }
      this.loading = false;
    },
  },
  beforeDestroy() {
    let fromTemp = this.$storage.getFromPo();
    if (fromTemp) {
      this.$storage.setFromPo(false);
    }
  },
};
</script>

<style lang="scss" scoped>
.gray-box {
  text-align: center;
  line-height: 30px;
  margin-right: 12px;
}
</style>
